package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Liangyaoyun
 */
public class leetCode1382 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }





    public TreeNode balanceBST(TreeNode root) {
        List<Integer>list=new ArrayList<>();
        middleOrderTraversal(root,list);
        return BuildTree(list,0,list.size()-1);
    }
    //中序遍历
    public void middleOrderTraversal(TreeNode root, List<Integer>list){
        if (root!=null){
            middleOrderTraversal(root.left,list);
            list.add(root.val);
            middleOrderTraversal(root.right,list);
        }
    }
    public TreeNode BuildTree(List<Integer>list,int left,int right){
        if (left>right){
            return null;
        }
        //跟节点
        int middle=(left+right)/2;
        TreeNode treeNode=new TreeNode(list.get(middle));
        treeNode.left=BuildTree(list,left,middle-1);
        treeNode.right=BuildTree(list,middle+1,right);
        return treeNode;
    }
}
